package cn.lbd;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class CuratorGetChild {
    private final String SOCKET_ADDRESS = "39.97.191.1:2181";
    CuratorFramework client;

    @Before
    public void init() {
        client = CuratorFrameworkFactory.builder()
                .connectString(SOCKET_ADDRESS)
                .sessionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("create_new")
                .build();

        client.start();
        System.out.println(client.isStarted());
    }

    @After
    public void destroy() {
        client.close();
    }

    @Test
    public void test1() throws Exception {
        //不指定任何节点路径就读取/create_new路径下的，因为这是创建连接对象时指定好的命名空间，所有操作基于这个节点下
        List<String> list = client.getChildren().forPath("");
        System.out.println(list.toString());
    }


    //异步方式读取
    @Test
    public void test2() throws Exception {
        client.getChildren()
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
                        System.out.println(curatorEvent.getType());
                        List<String> children = curatorEvent.getChildren();
                        System.out.println(children.toString());
                    }
                })
                .forPath("");
        TimeUnit.SECONDS.sleep(3);
        System.out.println("结束");
    }
}
